package gui.actions;

import gui.models.ConfigurationModel;

import java.util.List;

import javax.swing.JComponent;
import javax.swing.JOptionPane;

import common.Fictionator;
import common.interfaces.ConfigurationsInterface;
import common.types.FictionalCharacter;
import common.types.Pair;

public class QueryCharactersAction extends WorkerAction {

	private static final long serialVersionUID = 1L;
	private final ConfigurationModel model;
	private ConfigurationsInterface configurationsLogic;

	public QueryCharactersAction(JComponent owner, ConfigurationModel model) {
		super(owner);
		this.model = model;
		configurationsLogic = Fictionator.getInstance().getConfigurationsLogic();
	}
	
	@Override
	public boolean isAllowToRunOperation() {
		return true;
	}
	
	@Override
	public void runOperation() throws Exception {
		Pair<List<FictionalCharacter>, Integer> queryResult = configurationsLogic.getCharactersByName(model.getSearchName(), 10);
		model.setCharacters(queryResult.getLeft());
		model.setSearchResultsSize(queryResult.getRight());
	}
	
	@Override
	public void operationSucceed() {
		model.notifyObservers();
	}
	
	@Override
	public void operationFailed(Exception e) {
		e.printStackTrace();
		String errorMsg = "An error in database operation occured.\nThe following error occured: " + e.getLocalizedMessage() + "\nThe operation didn't take affect";
		String errorTitle = "Database query operation failed";
		JOptionPane.showMessageDialog(getOwner(), errorMsg, errorTitle, JOptionPane.ERROR_MESSAGE);
	}
	
}
